import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/common/widget/underline_text_field.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/login/application/notifier/login_apple_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_type_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_wechat_notifier.dart';
import 'package:casdon/modules/login/domain/states/login_apple_state.dart';
import 'package:casdon/modules/login/domain/states/login_wechat_state.dart';
import 'package:casdon/modules/login/domain/validators/input_validator.dart';
import 'package:casdon/modules/login/providers/login_apple_provider.dart';
import 'package:casdon/modules/login/providers/login_wechat_provider.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class BindAccountScreen extends ConsumerStatefulWidget {
  final String source;

  const BindAccountScreen({super.key, required this.source});

  @override
  ConsumerState<BindAccountScreen> createState() => _BindAccountScreenState();
}

class _BindAccountScreenState extends ConsumerState<BindAccountScreen> {
  final TextEditingController _controller = TextEditingController();
  ProviderSubscription<LoginWechatState>? _wechatLoginSubscription;
  ProviderSubscription<LoginAppleState>? _appleLoginSubscription;
  final bool _isLoading = false;

  @override
  void dispose() {
    _wechatLoginSubscription?.close();
    _appleLoginSubscription?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _listenLoginWechatState(context, ref);
    _listenLoginAppleState(context, ref);
    return KeyboardVisibilityBuilder(
      builder: (context, isKeyboardVisible) {
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: AppBar(title: const Text("")),
          body: SafeArea(
            child: SingleChildScrollView(
              padding: EdgeInsets.symmetric(horizontal: 24.h),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  SizedBox(height: 20.h),
                  Text(
                    "绑定账号",
                    style: context.textTheme.displayLarge?.copyWith(
                      color: context.customColorThemeNonNull.textColor1,
                    ),
                    textAlign: TextAlign.left,
                  ),
                  SizedBox(height: 24.h),
                  UnderlineTextField(
                    controller: _controller,
                    hintText: "手机号或邮箱",
                    keyboardType: TextInputType.emailAddress,
                    onChanged: (value) {
                      _onAccountChanged(value);
                    },
                    validator:
                        CombinedValidator.withDefaults().validateWithMessage,
                  ),
                  SizedBox(height: 32.h),
                  PrimaryButton(
                    text: "下一步",
                    isLoading: _isLoading,
                    onPressed: () {
                      _sendCode();
                    },
                  ),
                  if (isKeyboardVisible) const SizedBox(height: 300), // 给键盘留空间
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  void _sendCode() {
    final state = ref.read(loginTypeProvider);
    if (state == LoginType.wechat) {
      ref.read(loginWechatProvider.notifier).sendCode();
      return;
    }
    if (state == LoginType.apple) {
      ref.read(loginAppleProvider.notifier).sendCode();
      return;
    }
  }

  void _onAccountChanged(String value) {
    final state = ref.read(loginTypeProvider);
    if (state == LoginType.wechat) {
      ref.read(loginWechatProvider.notifier).setAccount(value);
      return;
    }
    if (state == LoginType.apple) {
      ref.read(loginAppleProvider.notifier).setAccount(value);
      return;
    }
  }

  void _listenLoginWechatState(BuildContext context, WidgetRef ref) {
    if (_wechatLoginSubscription != null) {
      return;
    }
    final notifier = ref.read(loginWechatProvider.notifier);
    _wechatLoginSubscription = ref.listenManual(loginWechatProvider, (
      previous,
      next,
    ) async {
      if (next.status == CommonNetStatus.failure) {
        if (notifier.step == WeChatLoginStep.sendCode) {
          // 发送验证码失败
          ToastUtil.show(next.message ?? "发送验证码失败");
        }
      } else if (next.status == CommonNetStatus.success) {
        if (notifier.step == WeChatLoginStep.sendCode) {
          context.router.push(CodeInputRoute(account: _controller.text));
        }
      }
    });
  }

  void _listenLoginAppleState(BuildContext context, WidgetRef ref) {
    if (_appleLoginSubscription != null) {
      return;
    }
    final notifier = ref.read(loginAppleProvider.notifier);
    _appleLoginSubscription = ref.listenManual(loginAppleProvider, (
      previous,
      next,
    ) async {
      if (next.status == CommonNetStatus.failure) {
        if (notifier.step == AppleLoginStep.sendCode) {
          // 发送验证码失败
          ToastUtil.show(next.message ?? "发送验证码失败");
        }
      } else if (next.status == CommonNetStatus.success) {
        if (notifier.step == AppleLoginStep.sendCode) {
          context.router.push(CodeInputRoute(account: _controller.text));
        }
      }
    });
  }
}
